<template>
  <div class="app-container">
    <a-title @clickPreview="preview" />
    <el-row :gutter="20" style="margin-bottom:20px" v-if="closureStatus">
      <el-col>
        <el-button
          v-for="item in flowNameList"
          :key="item.id"
          type="primary"
          @click="flowOpen(item)"
        >{{ item.showName }}</el-button>
      </el-col>
    </el-row>
    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="100px">
      <el-form-item label="校审流程名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入校审流程名称"
          clearable
          size="small"
          style="width: 240px"
          @keyup.enter.native="getList"
        />
      </el-form-item>
      <el-form-item label="流程状态" prop="flowStatus">
        <el-select
          v-model="queryParams.flowStatus"
          placeholder="请选择"
          clearable
          size="small"
          style="width: 240px"
        >
          <el-option
            v-for="item in options"
            :key="item.value"
            :label="item.text"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="发起时间">
        <el-date-picker
          v-model="queryParams.workflowStartTime"
          type="daterange"
          range-separator="-"
          value-format="yyyy-MM-dd"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          style="width: 240px"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="getList">查询</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <div class="tablebox">
      <el-table
        stripe
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @sort-change="tableSortChange"
        :default-sort="{prop: 'originTime', order: 'descending'}"
      >
        <el-table-column
          label="校审流程名称"
          prop="name"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="发起时间"
          prop="originTime"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        >
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.originTime) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          label="审批环节"
          prop="node"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column
          label="发起人"
          prop="origin"
          :sort-orders="['ascending', 'descending']"
          sortable="custom"
        />
        <el-table-column label="流程状态" prop="status">
          <template slot-scope="scope">
            <el-tag :type="scope.row.statusType" disable-transitions>{{ scope.row.statusText }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column width="120" label="操作">
          <template slot-scope="scope">
           <!-- 
            <a :href="scope.row.url" target="_blank">
              <i class="el-icon-view aicon"></i>查看流程
            </a>
            -->
            <a @click="skipWorkflow(scope.row)">
              <i class="el-icon-view aicon"></i>查看流程
            </a>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
    <!-- 预览 -->
    <el-dialog :visible.sync="openPreview" width="80%">
      <iframe :src="manualPreviewUrl" frameborder="0" width="100%" height="700px"></iframe>
    </el-dialog>

    <!-- 添加或修改报告号对话框 -->
    <el-dialog :title="请选择报告号" :visible.sync="openReport" width="60%" @close="cancel">
      <el-form ref="formReport" :model="formReport" label-width="80px">
        <el-form-item label="报告类型">
          <el-select
            v-model="referReport.referReportName"
            filterable
            placeholder="请选择报告类型"
            style="width:95%;"
            @change="getShowReportTypeBidding"
          >
            <el-option
              v-for="item in reportTypeOptions"
              :key="item.reportNo"
              :label="item.reportType"
              :value="item.reportNo"
            />
          </el-select>
          <span class="mustinput">*</span>
        </el-form-item>
        <el-form-item label="报告号" prop="reportTypeName">
          <el-select disabled v-model="referReport.referReportNo" placeholder style="width:95%;">
            <el-option v-for="item in reportNoOptions" :key="item" :label="item" :value="item" />
          </el-select>
          <span class="mustinput">*</span>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import axios from "axios";
import { checkBmsAgencyNo } from "@/api/projectWorkbench/projectList/agencyNo";
import { checkBmsCostNo } from "@/api/projectWorkbench/projectList/costNo";
import { listType } from "@/api/system/reportType";
import { Encrypt } from "@/utils/crypto";
import { getReportTypeList } from "@/api/projectWorkbench/projectList/reportNo";
import { getCostTypeList } from "@/api/projectWorkbench/projectList/costNo";
import aTitle from "@/components/Title";
import { resultsReviewList, flowList } from "@/api/business/resultsReview";
import { getArchiveAllStatus } from "@/api/business/dataArchive";
import { getBpmParams,checkTookPartIn } from "@/api/workflow/workflow";
import { checkBusiness } from "@/api/projectWorkbench/projectList/businessManagement"
import { checkProjectStatus } from "@/api/projectWorkbench/projectGlance";
import { getCategoryByGuid } from "@/api/system/business_category";


export default {
  name: "ResultsReview",
  components: { aTitle },
  data() {
    return {
      //项目结项状态
      closureStatus: false,
      archiveStatusDis: false,
      manualPreviewUrl: null,
      reportTypeCounts:0,
      openPreview: false,
      total: 0,
      loading: true,
      queryParams: {
        name: undefined,
        flowStatus: undefined,
        startDate: undefined,
        pageNum: 1,
        pageSize: 20,
        businessId: undefined,
        sortBy: undefined,
        order: undefined,
        workflowStartTime: undefined,
      },
      reportTypeOptions: [],
      reportNoOptions: [],
      referReport: {
        referReportName: undefined,
        referReportNo: undefined,
      },
      dateRange: [],
      flowNameList: [],
      dataItem: undefined,
      formReport: undefined,
      tableData: [],
      openReport: false,
      options: [
        { value: "0", text: "进行中" },
        { value: "1", text: "已完成" },
        { value: "2", text: "已取消" },
      ],
    };
  },
  created() {
    checkProjectStatus(this.$route.params.projectId).then(res=>{
      if(res.data){
        this.closureStatus = true;
      }
      
    });
    this.queryParams.businessId = this.$route.params.id;
    this.getFlowName();
    getArchiveAllStatus(this.queryParams.businessId).then((res) => {
      if (res.data.archiveStatus == "1" || res.data.archiveStatus == "2") {
        this.archiveStatusDis = true;
      }
    });
    //this.getList();
  },
  mounted(){
    document.title=document.getElementById("businessNameTitle").innerHTML;
  },
  methods: {
    cancel() {
      this.openReport = false;
    },
    preview() {
      this.openPreview = true;
      this.manualPreviewUrl = `${this.previewUrl}${encodeURIComponent(
        `${this.operationManual}业务主页/成果校审.xlsx`
      )}&name=${encodeURIComponent("成果校审.xlsx")}`;
    },
    getList() {
      this.loading = true;
      var reqParams = {
        businessId: this.queryParams.businessId,
        status: this.queryParams.flowStatus,
        name: this.queryParams.name,
        order: this.queryParams.order,
        pageNum: this.queryParams.pageNum,
        pageSize: this.queryParams.pageSize,
        sortBy: this.queryParams.sortBy,
        type: "1",
      };

      if (this.queryParams.workflowStartTime) {
        reqParams.originTimeStart = this.queryParams.workflowStartTime[0];
        reqParams.originTimeEnd = this.queryParams.workflowStartTime[1];
      }
      resultsReviewList(reqParams).then((res) => {
        if (res.code === 200) {
          this.tableData = res.rows.map((item) => {
            var jobNo = JSON.parse(sessionStorage.getItem("userinfo") || {})
              .jobNo;
              if(item.instanceUrl!=null&&item.instanceUrl!=""&&item.instanceUrl!==undefined){
                item.instanceUrl = item.instanceUrl.indexOf("InstanceId")==-1? item.instanceUrl+"&InstanceId="+item.instanceId:item.instanceUrl;
              }
              if(item.url!=null&&item.url!=""&&item.url!==undefined){
                item.url = item.url.indexOf("InstanceId")==-1? item.url+"&InstanceId="+item.instanceId:item.url;
              }
            /*
            if (item.status === "1") {
              item.url = item.instanceUrl + "&workState=1&code=" + jobNo;
            } else {
              if (jobNo === item.originNo) {
                item.url = item.url + "&code=" + jobNo;
              } else {
                item.url = item.instanceUrl + "&workState=2&code=" + jobNo;
              }
            }
            */

            if (item.status === "0") {
              item.statusText = "进行中";
              item.statusType = "primary";
            } else if (item.status === "1") {
              item.statusText = "已完成";
              item.statusType = "success";
            } else {
              item.statusText = "已取消";
              item.statusType = "info";
            }
            return item;
          });
          this.total = res.total;
          this.loading = false;
        }
      });
    },
    getFlowName() {
      flowList({
        businessCategoryId: this.$route.params.businessCategoryId,
      }).then((res) => {
        this.flowNameList = res.rows;
      });
    },
    flowOpen(item) {
      //先判断是否在本业务类别范围内
      checkBusiness(this.$route.params.projectId,this.$route.params.businessCategoryId).then(res=>{
        if(res.data===1){
          this.secFlowOpen(item);
        }else{
          this.msgError("本项目的服务范围不包含该业务的业务类别，请添加对应的服务范围再发起流程！");
        }
      });
    },
    secFlowOpen(item){
      this.reportTypeCounts = 0;
      
      this.dataItem = item;
      var rParam1 = {
        businessId: this.$route.params.id,
        businessType: this.$route.params.businessCategoryId,
      };

      var params = {
        businessTypeId: this.$route.params.businessCategoryId,
        projectId: this.$route.params.projectId,
        businessId: this.$route.params.id,
      };
      debugger;
      if (item.url === "ConsultingOutcomeDocument") {
        getReportTypeList(rParam1).then((res) => {
          if (res.code === 200) {
            if (res.data && res.data.length === 1) {
              if (res.data[0].reportNo && res.data[0].reportType) {
                params.reportNo = res.data[0].reportNo;
                if(this.reportTypeOptions.length>0){
                  this.reportTypeCounts =  this.reportTypeOptions.length;
                }else{
                  this.reportTypeCounts = 1;
                }
                this.getBpmParamsFun(params, item);
              } else {
                this.msgError(
                  "本业务暂无咨询报告号，请申请咨询报告号以后再发起"+item.showName+"！"
                );
                return false;
              }
            } else if (res.data.length > 1) {
              this.openReport = true;
              this.reportTypeOptions = res.data;
              this.reportTypeCounts =  res.data.length;
            } else {
              this.msgError(
                "本业务暂无咨询报告号，请申请咨询报告号以后再发起"+item.showName+"！"
              );
              return false;
            }
          }
        });
      } else if (item.url === "biddingDocument"  || item.url === "electronicTenderFileSeal") {
        
        var checkParams = {
          businessId: this.$route.params.id,
        };
        checkBmsAgencyNo(checkParams).then((res) => {
          if (res.code === 200 && res.data === 0) {
            this.msgError(
              "本业务暂无招标代理号，请申请招标代理号以后再发起"+item.showName+"！"
            );
          } else {
            this.reportTypeCounts = 1;
            this.getBpmParamsFun(params, item);
          }
        });
      } else if (item.url === "tenderAgentFileSeal") {
        var checkParams = {
          businessId: this.$route.params.id,
        };
        checkBmsAgencyNo(checkParams).then((res) => {
          if (res.code === 200 && res.data === 0) {
            this.msgError(
              "本业务暂无招标代理号，请申请招标代理号以后再发起"+item.showName+"！"
            );
          } else {
            this.reportTypeCounts = 1;
            this.getBpmParamsFun(params, item);
          }
        });
      } else if (item.url === "biddingInfoApplication") {
        var checkParams = {
          businessId: this.$route.params.id,
        };
        checkBmsAgencyNo(checkParams).then((res) => {
          if (res.code === 200 && res.data === 0) {
            this.msgError(
              "本业务暂无招标代理号，请申请招标代理号以后再发起"+item.showName+"！"
            );
          } else {
            this.reportTypeCounts = 1;
            this.getBpmParamsFun(params, item);
          }
        });
      } else if (item.url === "costConsultingReportSeal") {
        getCostTypeList(rParam1).then((res) => {
          if (res.code === 200) {
            if (res.data && res.data.length === 1 && res.data[0]!=null) {
              if (res.data[0].costNo && res.data[0].costType) {
                params.costNo = res.data[0].costNo;
                params.reportType = res.data[0].costType;
                this.reportTypeCounts = 1;
                this.getBpmParamsFun(params, item);
              } else {
                this.msgError(
                  "本业务暂无造价报告号，请申请造价报告号以后再发起"+item.showName+"！"
                );
                return false;
              }
            } else if (res.data.length > 1) {
              this.openReport = true;
              this.reportTypeOptions = res.data;
            } else {
              this.msgError(
                "本业务暂无造价报告号，请申请造价报告号以后再发起"+item.showName+"！"
              );
              return false;
            }
          }
        });
      }/*else if(item.url === "environmentalResultReview"){
        getCategoryByGuid(params.businessTypeId).then(res=>{
          if(res.code === 200){
            params.reportType = res.data.reportName;
            this.getBpmParamsFun(params, item);
          }
        });

      } */else {
        this.reportTypeCounts = 0;
        this.getBpmParamsFun(params, item);
      }
    },
    getBpmParamsFun(params, item) {
      getBpmParams(params).then((res) => {
        if (res.code === 200) {
          res.data.reportType = params.reportType;
          this.gotoBpm(res.data, item);
        }
      });
    },
    submitForm() {
      if (
        !this.referReport.referReportName &&
        !this.referReport.referReportNo
      ) {
        this.msgError("报告号不能为空！");
        return false;
      }

      var params = {
        businessTypeId: this.$route.params.businessCategoryId,
        projectId: this.$route.params.projectId,
        businessId: this.$route.params.id,
        reportNo: this.referReport.referReportNo,
      };
      this.getBpmParamsFun(params, this.dataItem);
    },
    gotoBpm(data, item) {
      debugger;
      var bpmUrl = this.bpmUrl;
      var rParam = {
        businessCategoryId: data.businessCategoryId,
        businessCategory: data.businessCategory,
        projectId: data.projectId,
        businessId: data.businessId,
        businessName: data.businessName,
        deptId: data.deptId,
        deptName: data.deptName,
        projectLeader: data.projectLeader,
        projectLeaderId: data.projectLeaderId,
        projectName: data.projectName,
        projectManager: data.projectManager,
        projectLeaderNo: data.projectLeaderNo,
        projectManagerNo: data.projectManagerNo,
        projectCode: data.projectCode,
        reportName: data.reportName,
        members: data.members,
        referReportName: data.referReportName,
        reportNo: data.reportNo,
        reportId: data.reportId,
        projectGlobalId: data.projectGlobalId,
        businessNo: data.businessNo == null ? "" : data.businessNo,
        agencyId: data.agencyId == null ? "" : data.agencyId,
        agencyNo: data.agencyNo == null ? "" : data.agencyNo,
        sectionName: data.sectionName == null ? "" : data.sectionName,
        agencyName: data.agencyName == null ? "" : data.agencyName,
        otherNo: data.otherNo == null ? "" : data.otherNo,
        applicationNo: data.applicationNo == null ? "" : data.applicationNo,

        costName: data.costName == null ? "" : data.costName,
        costNo: data.costNo == null ? "" : data.costNo,
        costId: data.costId == null ? "" : data.costId,
        reportType: data.reportType == null ? "" : data.reportType,
        reportTypeCounts:this.reportTypeCounts,

        projectCompany: data.projectCompany == null ? "" : data.projectCompany,
        executeDept: data.executeDept == null ? "" : data.executeDept,

        agencyProjectLeaderId: data.agencyProjectLeaderId == null ? "" : data.agencyProjectLeaderId,
        agencyProjectLeader: data.agencyProjectLeader == null ? "" : data.agencyProjectLeader,
        agencyProjectLeaderNo: data.agencyProjectLeaderNo == null ? "" : data.agencyProjectLeaderNo
      };

      axios
        .post(bpmUrl + "/Portal/InstanceController/starInstance", rParam)
        .then(function (response) {
          if (response.status == 200 && response.data) {
            debugger;
            var code = JSON.parse(sessionStorage.getItem("userinfo") || {})
              .jobNo;
            //code = Encrypt(code);
            window.open(
              bpmUrl +
                "/Portal/run.html?workflowCode=" +
                item.url +
                "&formId=" +
                response.data.formId +
                "&date=" +
                response.data.date +
                "&code=" +
                code
            );
          }
        })
        .catch(function (error) {
          console.log(error);
        });
    },
    resetQuery() {
      this.dateRange = [];

      this.queryParams.name = undefined;
      this.queryParams.flowStatus = undefined;
      this.queryParams.workflowStartTime = undefined;

      this.resetForm("queryParams");
      this.getList();
    },
    tableSortChange(column) {
      this.queryParams.pageNum = 1;
      if (column.order === "descending") {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "desc";
      } else {
        this.queryParams.sortBy = column.prop;
        this.queryParams.order = "asc";
      }
      this.getList();
    },
    getShowReportTypeBidding(val) {
      if (val) {
        for (var i = 0; i < this.reportTypeOptions.length; i++) {
          if (this.reportTypeOptions[i].reportNo === val) {
            this.reportNoOptions = [];
            this.reportNoOptions.push(val);
            this.referReport.referReportNo = val;
          }
        }
      } else {
        this.referReport.referReportNo = "";
      }
    },
    skipWorkflow(row){
      var lookBpmJobNo = this.lookBpmJobNo;
      var jobNo = JSON.parse(sessionStorage.getItem("userinfo") || {})
              .jobNo;
      var params = {
        jobNo: jobNo,
        instanceId: row.instanceId
      };
      checkTookPartIn(params).then(res=>{
        if(res.code===200){
          if(res.data===1){
            if (row.status === "1") {
              row.url = row.instanceUrl + "&workState=1&code=" + jobNo;
            } else {
              if (jobNo === row.originNo) {
                row.url = row.url + "&code=" + jobNo;
              } else {
                row.url = row.instanceUrl + "&workState=2&code=" + jobNo;
              }
            }
            window.open(row.url); 
          }else{
            window.open(row.instanceUrl+ "&workState=2&code=" + lookBpmJobNo); 
          }
        }
      });
      
    }
  },
};
</script>
<style lang="scss" scoped>
.tablebox {
  height: 100%;
}
/deep/.el-table .cell {
  font-family: PingFangSC-Regular;
  color: rgba(0, 0, 0, 0.85);
  letter-spacing: 0;
  text-align: center;
  a {
    font-family: PingFangSC-Regular;
    font-size: 14px;
    color: #1890ff;
    letter-spacing: 0;
    text-align: right;
    line-height: 14px;
    margin: 0 10px;
  }
}
</style>
